package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-08-09
 * Time: 14:59
 */
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient (String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }
    public void start() {
        System.out.println("客户端启动");
        Scanner scannerConsole = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            while (true) {
                System.out.print("-> ");
                String requestConsole = scannerConsole.next();
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(requestConsole);
                printWriter.flush();
                Scanner scannerNetwork = new Scanner(inputStream);
                String response = scannerNetwork.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
